package page

import (
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
	"reflect"
)

// http 分页对象
type HttpPage struct {
	PageSize int  `json:"page_size"`
	Page     int  `json:"page"`
	NoPage   bool `json:"no_page"`
	Total    int  `json:"total"`
}

func (page *HttpPage) Limit() int {
	return page.PageSize
}

func (page *HttpPage) Offset() int {
	offset := (page.Page - 1) * page.PageSize
	return offset
}

// constructor
func NewHttpPage(r *ghttp.Request) *HttpPage {
	page := r.GetQueryInt("page")
	pageSize := r.GetQueryInt("page_size")
	noPage := r.GetQueryBool("no_page")

	if page <= 0 {
		page = 1
	}

	if pageSize <= 0 {
		pageSize = 15
	}

	return &HttpPage{
		PageSize: pageSize,
		Page:     page,
		NoPage:   noPage,
	}
}

// 打包分页数据
func (page *HttpPage) PageMapPack(data *g.Map) *g.Map {
	if !page.NoPage {
		(*data)["page"] = page.Page
		(*data)["page_size"] = page.PageSize
		(*data)["total"] = page.Total
	}

	return data
}

// 动态分页 i, o 均 为 model 层中的 *arModel 类型
func (page *HttpPage) Pagination(i interface{}) (o interface{}) {
	if !page.NoPage {
		value := reflect.ValueOf(i)
		param := make([]reflect.Value, 2)
		param[0] = reflect.ValueOf(page.Page)
		param[1] = reflect.ValueOf(page.Limit())
		rs := value.MethodByName("Page").Call(param)
		o = rs[0].Interface()

		rs = value.MethodByName("Count").Call(nil)

		page.Total = rs[0].Interface().(int)
	} else {
		o = i
	}
	return
}
